package com.snopy.concurrency.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author snopy
 * @version 1.0.0
 * @classname DemoThreadPool
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/30 14:15
 */
@Slf4j
public class DemoThreadPool {



    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = new ThreadPoolExecutor(3,3,0, TimeUnit.SECONDS,new ArrayBlockingQueue<>(5));
        Collection<Callable<String>> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            int k = i;
            list.add(() -> {
                log.debug("begin...");
                TimeUnit.SECONDS.sleep(k);
                log.debug("end...");
                return "task"+k;
            });
        }
 /*       list.forEach(t->{
            try {
                t.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });*/
        List<Future<String>> futures = executor.invokeAll(list);
        futures.forEach(r-> {
            try {
                System.out.println(r.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
        executor.shutdown();
    }
}
class Task implements Callable{
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public Object call() throws Exception {
        return "123";
    }
}